package com.ytf.auth.authentication.service;

import com.ytf.auth.authentication.SmsAuthenticationToken;
import com.ytf.auth.common.CommonParam;
import com.ytf.core.web.application.UserAppService;
import com.ytf.core.web.pojo.vo.RoleVo;
import com.ytf.core.web.pojo.vo.UserVo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @className: SmsAuthenticationProvider
 * @author: YTF
 * @date: 2025/5/1 10:46
 * @description:
 */
@Component
@RequiredArgsConstructor
public class SmsAuthenticationProvider implements AuthenticationProvider {

    private final UserAppService userAppService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String phone = (String) authentication.getPrincipal();
        String code = (String) authentication.getCredentials();

        // 明确调用手机号查询方法
        UserVo userVo = userAppService.getByMobile(phone);
        List<RoleVo> roleVos = userVo.getRoleVos();
        // 将 List 转换为 String 数组
        String[] array = roleVos.stream().map(RoleVo::getRoleKey).toArray(String[]::new);

        UserDetails user = User.builder()
                .username(userVo.getUsername())
                .password(userVo.getPassword())
                .roles(array)
                .build();

        // 验证验证码
        Map<String, String> captcha = CommonParam.CAPTCHA;
        if (captcha.get(phone) == null || !captcha.get(phone).equals(code)) {
            throw new BadCredentialsException("验证码错误");
        }

        return new SmsAuthenticationToken(user, null, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (SmsAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
